// 1、无头单向非循环链表实现
public class SingleLinkedList {
    //头插法
    public void addFirst(int data) {
        ListNode node = new  ListNode(data);
        ListNode cur = head;

        if(head == null) {
            head = node;
        }else {
           node.next = head;
           head = node;
        }
    }
    //尾插法
    public void addLast(int data){
        ListNode node = new  ListNode(data);

        if(head == null) {
            head = node;
            return;
        }

        SingleLinkedList cur = head;
        while(cur.next != null) {
            cur = cur.next;
        }

         cur.next = node;

    }






    //任意位置插入,第一个数据节点为0号下标
    public boolean addIndex(int index,int data) {
        if(index == 0) {
            addFirst(data);
            return;
        }

        if(index == size()) {
            addLast(data);
            return;
        }

        ListNode cur = Findindex(index);

        ListNode node = new ListNode(data);

        node.next = cur.next;
        cur.next = node;
    }

    public ListNode Findindex(int index) {
        ListNode cur = head;
        int i = 0;
        while(i != index-1) {
            cur = cur.next;
            i++;
        }
        return cur;
    }






    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key) {
        ListNode cur = head;
        while(cur != null) {
            if(cur.val == key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }




    //删除第一次出现关键字为key的节点
    public void remove(int key) {
        if(head == null) {
            return;
        }
        if(head.val == key) {
            head= head.next;
            return;
        }
        ListNode cur = findkey(key);
        if(cur == null) {
            return;
        }

        cur.next = cur.next.next;
    }

    public ListNode findkey(int key) {
        ListNode cur = head;
        while(cur.next != null) {
            if(cur.next.val == key) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }






    //删除所有值为key的节点
    public void removeAllKey(int key);
    //得到单链表的长度

    public int size() {
        ListNode cur = head;
        int i = 0;
        while(cur != null) {
            i++;
            cur = cur.next;
        }
        return i;
    }

    public void display() {
        ListNode cur = head;

        while(cur != null) {
            System.out.println(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }
    public void clear() {

    }

}